package com.example.java_chatroom.Controller;

import com.example.java_chatroom.model.FriendApply;
import com.example.java_chatroom.model.FriendInfo;
import com.example.java_chatroom.model.Result;
import com.example.java_chatroom.model.UserInfo;
import com.example.java_chatroom.service.*;
import com.example.java_chatroom.utils.GetUserInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RequestMapping("/userInfo")
@RestController
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private FriendInfoService friendInfoService;

    @Autowired
    private FriendApplyService friendApplyService;
    @Autowired
    private MessageSessionService messageSessionService;
    @Autowired
    private MessageService messageService;
    @RequestMapping("/deleteUserInfo")
    public Result deleteUserInfo(Integer userId,HttpServletRequest request) {
        //首先先删除用户数据
        userInfoService.deleteUserByUserId(userId);
        //删除用户数据中的好友
        friendInfoService.deleteFriendByUserId(userId);

        //删除用户数据中的会话message_session_user
        List<Integer> list = messageSessionService.queryUserSessionIdByuserId(userId);
        System.out.println(list.toString());
        for(Integer sessionId :list) {
                List<Integer> list1 = messageSessionService.queryUserIdBysessionId(sessionId);
            System.out.println(list1.toString());
            if (list1.size() > 2) {
                messageSessionService.deleteSessionUserBySessionIdANDUserId(sessionId, userId);
            } else if (list1.size() == 2) {
                messageSessionService.deleteSessionUser(sessionId);
                messageSessionService.deleteSession(sessionId);
                        //删除两个人聊天数据
                messageService.deleteMessage(sessionId);
            }
        }

        HttpSession session = request.getSession(true);
        session.removeAttribute("userInfo");
        //删除用户数据的会话信息
        return Result.success(1);

    }

    @RequestMapping("/updateUserInfo")
    public Result updateUserInfo(String userName, Integer userId,HttpServletRequest request) {
       List<UserInfo> list =  userInfoService.queryUserInfoAll();
        for (UserInfo userInfo1 : list) {
            if (userInfo1.getUserName().equals(userName)) {
                return Result.fail("用户名已存在");
            }
        }
        userInfoService.updateUserInfo(userId, userName);
        UserInfo userInfo = userInfoService.queryUserById(userId);
        request.getSession().setAttribute("userInfo", userInfo);
        return Result.success(userInfo);
    }
    @RequestMapping("/login")
    public Result login(String userName, String password, HttpServletRequest request) {
        System.out.println(userName + " " + password);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户或者密码不能为空");
        }
        System.out.println("ada");
        UserInfo userInfo = userInfoService.queryUserByName(userName);
        System.out.println("213");
        if (userInfo == null || userInfo.getUserId() < 0 || !password.equals(userInfo.getPassword())) {
            return Result.fail("用户不存在或密码错误");
        }
        System.out.println("12345");
        if (userInfo.getCode() == 0) {
            userInfoService.updateCode(0, userName);
            userInfo.setCode(1);
            userInfo.setPassword("");
            HttpSession session = request.getSession(true);
            session.setAttribute("userInfo", userInfo);
            return Result.success(userInfo);
        } else {
            return Result.fail("用户已经登陆");
        }

    }

    @RequestMapping("/register")
    public Result register(UserInfo userInfo) {
        try {
            userInfoService.insert(userInfo);
        } catch (DuplicateKeyException e) {
            //如果抛出这个异常表示名字重复了，注册失败
            log.error("名字重复");
            return Result.fail("名字重复,注册失败");
        }
        System.out.println(userInfo.toString());
        return Result.success(true);
    }

    @RequestMapping("getUserInfoByUserId")
    public Result getUserInfoByUserId(Integer userId) {
        UserInfo userInfo = userInfoService.queryUserById(userId);
        if (userInfo == null) {
            return Result.fail("错误");
        }
        return Result.success(userInfo);
    }
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return Result.fail("[getUserInfo] 当前获取不到 Session 对象！");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            return Result.fail("没有找到UserInfo对象");
        }
        return Result.success(userInfo);
    }

    @RequestMapping("/addFriend")
    public Result addFriend(String name, HttpServletRequest request) {
        UserInfo userInfo1 = userInfoService.queryUserByName(name);
        if (userInfo1 == null) {
            return Result.fail("用户不存在");
        } else {
            UserInfo userInfo = GetUserInfoUtils.getUserInfo(request);
            if (userInfo == null) {
                return Result.fail(null);
            }
            //根据userId从数据库查询数据
            List<FriendInfo> lists = friendInfoService.getFriendList(userInfo.getUserId());
            for (FriendInfo friendInfo : lists) {
                if (name.equals(friendInfo.getFriendName())) {
                    return Result.success(name);
                }
            }

            friendInfoService.insertfriend(userInfo.getUserId(), userInfo1.getUserId());
            return Result.success(1);

        }
    }

    @RequestMapping("/requestFriend")
    public Result requestFriend(String friend, String argument, HttpServletRequest request) {
        System.out.println(friend + "argument:" + argument);
        UserInfo userInfo = GetUserInfoUtils.getUserInfo(request);
        if (userInfo == null) {
            return Result.fail(null);
        }
        if (!StringUtils.hasLength(friend) || !StringUtils.hasLength(argument)) {
            return Result.fail("请输入理由");
        }
        List<FriendApply> list = friendApplyService.queryFriendNameByUserName(userInfo.getUserName());
        for (FriendApply friendApply : list) {
            System.out.println("friendApply"+friendApply.getFriend());
            System.out.println("   x"+friend);
            if (friendApply.getFriend().equals(friend)) {
                Integer i = friendApplyService.updateFriendApply(argument,friend , userInfo.getUserName());
                if (i > 0) {
                    return Result.success(1);
                } else {
                    return Result.fail(null);
                }
            }
        }
        Integer i = friendApplyService.insertFriendApply(friend, argument, userInfo.getUserName());
        if (i > 0) {
            return Result.success(1);
        } else {
            return Result.fail(null);
        }

    }

    @RequestMapping("/queryFriend")
    public Result queryFriend(String message, HttpServletRequest request) {
        UserInfo userInfo1 = GetUserInfoUtils.getUserInfo(request);
        if (userInfo1 == null) {
            return Result.fail(null);
        }
        if (message == "" || message == null) {
            return Result.fail("输入框不能为空");
        }
        List<String> lists = userInfoService.queryUserByNames(message + "%", userInfo1.getUserId());
        System.out.println(lists.toString());
        if (lists != null) {
            if (lists.size() == 0) {
                return Result.fail("用户不存在");
            } else {
                return Result.success(lists);
            }
        }

        return Result.fail("用户没注册");
    }
}
